package cn.drenal.capcap.service.impl;

import cn.drenal.capcap.entity.SysRole;
import cn.drenal.capcap.entity.SysRolePermission;
import cn.drenal.capcap.entity.dto.RoleDTO;
import cn.drenal.capcap.entity.dto.RolePermissionDTO;
import cn.drenal.capcap.exception.BizException;
import cn.drenal.capcap.mapper.SysRoleMapper;
import cn.drenal.capcap.mapper.SysRolePermissionMapper;
import cn.drenal.capcap.service.SysRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    private final SysRolePermissionMapper rolePermissionMapper;

    @Override
    public SysRole createRole(RoleDTO roleDTO) {
        // 检查角色编码是否已存在
        if (lambdaQuery().eq(SysRole::getCode, roleDTO.getCode()).exists()) {
            throw new BizException("角色编码已存在");
        }

        // 创建角色对象
        SysRole role = new SysRole();
        role.setName(roleDTO.getName());
        role.setCode(roleDTO.getCode());
        role.setDescription(roleDTO.getDescription());
        role.setStatus(roleDTO.getStatus());

        // 保存角色
        save(role);
        return role;
    }

    @Override
    public SysRole updateRole(Long id, RoleDTO roleDTO) {
        // 检查角色是否存在
        SysRole role = getById(id);
        if (role == null) {
            throw new BizException("角色不存在");
        }

        // 检查角色编码是否已存在（排除自身）
        if (lambdaQuery().eq(SysRole::getCode, roleDTO.getCode()).ne(SysRole::getId, id).exists()) {
            throw new BizException("角色编码已存在");
        }

        // 更新角色信息
        role.setName(roleDTO.getName());
        role.setCode(roleDTO.getCode());
        role.setDescription(roleDTO.getDescription());
        role.setStatus(roleDTO.getStatus());

        // 保存更新
        updateById(role);
        return role;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Long id) {
        // 检查角色是否存在
        if (!lambdaQuery().eq(SysRole::getId, id).exists()) {
            throw new BizException("角色不存在");
        }

        // 删除角色权限关联
        rolePermissionMapper.delete(new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, id));

        // 删除角色
        removeById(id);
    }

    @Override
    public Page<SysRole> getRoleList(Page<SysRole> page, String name, String code) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasText(name)) {
            queryWrapper.like(SysRole::getName, name);
        }
        if (StringUtils.hasText(code)) {
            queryWrapper.like(SysRole::getCode, code);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(SysRole::getCreateTime);
        
        return page(page, queryWrapper);
    }

    @Override
    public List<SysRole> getAllRoles() {
        return lambdaQuery().eq(SysRole::getStatus, 1).orderByAsc(SysRole::getCreateTime).list();
    }

    @Override
    public SysRole getRoleById(Long id) {
        SysRole role = getById(id);
        if (role == null) {
            throw new BizException("角色不存在");
        }
        return role;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRolePermission(RolePermissionDTO rolePermissionDTO) {
        Long roleId = rolePermissionDTO.getRoleId();
        List<Long> permissionIds = rolePermissionDTO.getPermissionIds();
        
        // 检查角色是否存在
        if (!lambdaQuery().eq(SysRole::getId, roleId).exists()) {
            throw new BizException("角色不存在");
        }
        
        // 删除原有的角色权限关联
        rolePermissionMapper.delete(new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, roleId));
        
        // 如果权限ID列表为空，则不添加新的权限
        if (permissionIds == null || permissionIds.isEmpty()) {
            return;
        }
        
        // 批量添加新的角色权限关联
        List<SysRolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionId : permissionIds) {
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissions.add(rolePermission);
        }
        
        // 批量保存
        rolePermissionMapper.insertBatchSomeColumn(rolePermissions);
    }

    @Override
    public List<Long> getRolePermissionIds(Long roleId) {
        // 检查角色是否存在
        if (!lambdaQuery().eq(SysRole::getId, roleId).exists()) {
            throw new BizException("角色不存在");
        }
        
        // 查询角色权限关联
        List<SysRolePermission> rolePermissions = rolePermissionMapper.selectList(
                new LambdaQueryWrapper<SysRolePermission>().eq(SysRolePermission::getRoleId, roleId));
        
        // 提取权限ID列表
        return rolePermissions.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
    }
}